<template>
  <Modal :title="!dataForm.id ? '新增' : '修改'"
         id="user-management-add-update"
         width="600px"
         :mask-closable="false"
         v-model="visible"
         okText="保存">

    <Form class="clearfix form-custom"
          ref="formCustom"
          :model="dataForm"
          :rules="ruleCustom"
          :label-width="80">
      <FormItem label="昵称"
                prop="loginName">
        <Input v-model="dataForm.loginName"
               placeholder="设置登录用户名"></Input>
      </FormItem>
      <FormItem label="真实姓名"
                prop="name">
        <Input v-model="dataForm.name"
               placeholder="真实姓名"></Input>
      </FormItem>
      <FormItem label="密码"
                prop="password">
        <Input type="password"
               v-model="dataForm.password"
               placeholder="设置登录密码"></Input>
      </FormItem>
      <FormItem label="确认密码"
                prop="passwdCheck">
        <Input type="password"
               v-model="dataForm.passwdCheck"></Input>
      </FormItem>
      <FormItem label="角色">
        <Select v-if="dataForm.roleId==1"
                v-model="dataForm.roleId"
                disabled
                style="width:204px">
          <Option :value="dataForm.roleId">管理员</Option>
        </Select>
        <Select v-else
                v-model="dataForm.roleId"
                style="width:204px">
          <Option v-for="item in options"
                  :value="item.value"
                  :key="item.value">{{ item.label }}</Option>
        </Select>

      </FormItem>
      <FormItem v-if="dataForm.roleId===3"
                label="班级"
                prop="no">
        <div>格式：18级XX系02班</div>
        <Input v-model="dataForm.no"
               placeholder="按照上面格式填写"></Input>
      </FormItem>
      <FormItem label="联系电话"
                prop="mobile">
        <Input v-model="dataForm.mobile"></Input>
      </FormItem>
      <FormItem class="clearfix"
                label="联系邮箱"
                prop="email">
        <Input v-model="dataForm.email"></Input>
      </FormItem>
    </Form>
    <div>头像上传</div>

    <div class="demo-upload-list"
         v-if="this.uploadList.length">
      <template>
        <img :src="avatarUrl">
        <div class="demo-upload-list-cover">
          <Icon type="ios-eye-outline"
                @click.native="handleView()"></Icon>
          <Icon type="ios-trash-outline"
                @click.native="handleRemove()"></Icon>
        </div>
      </template>
    </div>
    <Upload ref="upload"
            :show-upload-list="false"
            :default-file-list="defaultList"
            :on-success="handleSuccess"
            :format="['jpg','jpeg','png']"
            :max-size="2048"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :before-upload="handleBeforeUpload"
            type="drag"
            action="//jsonplaceholder.typicode.com/posts/"
            style="display: inline-block;width:58px;">
      <div style="width: 58px;height:58px;line-height: 58px;">
        <Icon type="ios-camera"
              size="20"></Icon>
      </div>
    </Upload>
    <Modal title="头像剪裁"
           v-model="visible2"
           :loading="loading2"
           :mask-closable="false"
           @on-ok="avatarOk">
      <div class="cropper-content"
           v-if="visible2">
        <div class="cropper">
          <vueCropper ref="cropper"
                      :img="previewUrl"
                      :canScale="option.canScale"
                      :fixedNumber="option.fixedNumber"
                      :fixed="option.fixed"
                      :centerBox="false"
                      :autoCrop="true"
                      :canMove="false"
                      :mode="option.mode"
                      @realTime="realTime"></vueCropper>
        </div>

        <div :style="previewStyle1">
          <div :style="previews.div">
            <img :src="previews.url"
                 :style="previews.img">
          </div>
        </div>

        <!-- <div :style="previewStyle2"> 
                <div :style="previews.div">
                  <img :src="previews.url" :style="previews.img">
                </div>
              </div> -->

      </div>
    </Modal>
    <div slot="footer"
         class="footer">
      <Button type="primary"
              @click="visible=false">取消</Button>
      <Button type="primary"
              @click="dataFormSubmit">确认</Button>
    </div>
  </Modal>
</template>

<script>
import { addUser, uploadPhoto, updateUser, queryCheckUser } from '@/api/management.js'
import { VueCropper } from 'vue-cropper'
export default {
  data () {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.dataForm.passwdCheck !== '') {
          // 对第二个密码框单独验证
          this.$refs.formCustom.validateField('passwdCheck')
        }
        callback()
      }
    }
    const validatePassCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请确认密码'))
      } else if (value !== this.dataForm.password) {
        callback(new Error('两次密码输入不一致!'))
      } else {
        callback()
      }
    }
    const telCheck = (rule, value, callback) => {
      if (value === '' || value == null) {
        callback()
      } else {
        if (!/^1[34578]\d{9}$/.test(value)) {
          callback(new Error('请输入正确的电话号码'))
        } else {
          callback()
        }
      }
    }
    const classesCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请按照示例格式输入班级'))
      } else {
        // /^1[34578]\d{9}$/
        if (!/^\d{2}级\S*系\d{2}班$/.test(value)) {
          callback(new Error('输入格式有误'))
        } else {
          callback()
        }
      }
    }
    return {
      visible: false,
      dataForm: {
        loginName: '',
        roleId: 0,
        no: '',
        password: '',
        passwdCheck: '',
        roleName: '',
        name: '',
        email: '',
        mobile: '',
        photo: ''
      },
      defaultList: [
        {
          name: 'a42bdcc1178e62b4694c830f028db5c0',
          url:
            'https://o5wwk8baw.qnssl.com/a42bdcc1178e62b4694c830f028db5c0/avatar'
        },
        {
          name: 'bc7521e033abdd1e92222d733590f104',
          url:
            'https://o5wwk8baw.qnssl.com/bc7521e033abdd1e92222d733590f104/avatar'
        }
      ],
      imgName: '',
      visible2: false,
      // 上传列表
      uploadList: [],
      // 下拉选框
      options: [
        {
          value: 3,
          label: '学生'
        },
        {
          value: 2,
          label: '老师'
        },
        {
          value: 4,
          label: '专家'
        }
      ],
      // 校验规则
      ruleCustom: {
        password: [{ validator: validatePass, trigger: 'blur' }],
        passwdCheck: [{ validator: validatePassCheck, trigger: 'blur' }],
        name: [
          {
            required: true,
            message: '请填写真实姓名',
            trigger: 'blur'
          },
        ],
        loginName: [
          {
            required: true,
            message: '请填写昵称',
            trigger: 'blur'
          },
          { validator: this.checkUser, trigger: 'blur' }
        ],
        roleId: [
          {
            required: true,
            message: '请选择角色',
            trigger: 'blur'
          }
        ],
        no: [{ validator: classesCheck, trigger: 'blur' }],
        email: [{ type: 'email', message: '邮箱格式错误', trigger: 'blur' }],
        mobile: [{ validator: telCheck, trigger: 'blur' }]
      },
      // 判断新增还是修改
      addNew: true,
      option: {
        img: 'http://img1.vued.vanthink.cn/vued751d13a9cb5376b89cb6719e86f591f3.png',
        canScale: false,
        fixed: true,
        fixedNumber: [1, 1],
        fixedBox: true,
        mode: 'cover'
      },
      avatarUrl: '',
      previewUrl: '',
      previews: "",
      previewStyle1: '',
      previewStyle2: '',
      loading2: false
    }
  },
  components: {
    VueCropper,
  },
  methods: {
    init (row) {
      this.visible = true
      this.$nextTick(() => {
        if (row) {
          this.addNew = false
          this.dataForm = row
          this.dataForm['passwdCheck'] = row.password
        } else {
          this.dataForm = {
            loginName: '',
            roleId: 0,
            no: '',
            password: '',
            roleName: '',
            name: '',
            email: '',
            mobile: '',
            photo: ''
          }
        }
      })
    },
    // 表单提交
    dataFormSubmit () {
      if (this.addNew) {
        if (this.uploadList.length > 0) {
          this.$refs['formCustom'].validate(valid => {

            if (valid) {
              let data = new FormData()
              data.append('loginName', this.dataForm.loginName)
              data.append('mf', this.uploadList[0])
              uploadPhoto(data).then(res => {

                if (res.data && res.data != 'fail') {
                  let data = {}
                  for (let key in this.dataForm) {
                    if (key !== 'passwdCheck') {
                      data[key] = this.dataForm[key]
                    }
                  }
                  data['photo'] = res.data
                  addUser(data).then(res => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  })
                }
              })
            }
          })
        } else {
          this.$Message.warning('请选择一张头像')
        }
      } else {

        if (this.uploadList.length > 0) {
          this.$refs['formCustom'].validate(valid => {
            if (valid) {
              let data = new FormData()
              data.append('loginName', this.dataForm.loginName)
              data.append('mf', this.uploadList[0])
              uploadPhoto(data).then(res => {
                if (res.data && res.data != 'fail') {
                  let data = {}
                  for (let key in this.dataForm) {
                    if (key !== 'passwdCheck') {
                      data[key] = this.dataForm[key]
                    }
                  }
                  data['photo'] = res.data
                  updateUser(data).then(res => {

                  })
                }
              })
            }
          })
        } else {

          this.$refs['formCustom'].validate(valid => {
            if (valid) {
              let data = {}
              for (let key in this.dataForm) {
                if (key !== 'passwdCheck') {
                  data[key] = this.dataForm[key]
                }
              }
              updateUser(data).then(res => {
                if (res.data === 'success') {
                  this.$emit('refreshDataList')
                  this.visible = false
                }
              })
            }
          })
        }
      }
    },
    // 图片上传组件
    handleView (name) {
      this.imgName = name
      this.visible2 = true
    },
    handleRemove () {
      this.uploadList = []
      this.avatarUrl = ''
    },
    handleSuccess (res, file) {
      file.url =
        'https://o5wwk8baw.qnssl.com/7eb99afb9d5f317c912f08b5212fd69a/avatar'
      file.name = '7eb99afb9d5f317c912f08b5212fd69a'
    },
    handleFormatError (file) {
      this.$Notice.warning({
        title: 'The file format is incorrect',
        desc:
          'File format of ' +
          file.name +
          ' is incorrect, please select jpg or png.'
      })
    },
    handleMaxSize (file) {
      this.$Notice.warning({
        title: 'Exceeding file size limit',
        desc: 'File  ' + file.name + ' is too large, no more than 2M.'
      })
    },
    handleBeforeUpload (file) {
      if (
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'image/jpeg'
      ) {
        let reader = new FileReader()
        reader.readAsDataURL(file)
        const _this = this
        reader.onloadend = function (e) {
          _this.visible2 = true
          _this.loading2 = true
          _this.previewUrl = reader.result
          // _this.avatarUrl = reader.result
          // _this.uploadList = [file]
        }
      } else {
        this.$Message.error('请选择格式为png、jpg、jpeg的图片')
      }

      return false
    },
    // 检查用户名是否存在
    checkUser (rule, value, callback) {
      if (this.addNew) {
        if (value != '') {
          queryCheckUser(this.dataForm.loginName).then((res) => {
            if (res.data == '0') {
              callback()
            } else {
              callback(new Error('该用户名已被注册'))
            }
          })
        }
      } else {
        callback()
      }

    },
    avatarOk () {
      // file
      this.$refs.cropper.getCropData((data) => {
        // do something

        this.avatarUrl = data

        this.uploadList = [this.dataURLtoFile(data, 'qq.jpg')]
        this.visible2 = false
      })

      // blob

      // this.$refs.cropper.getCropBlob((data) => {
      //   // do something
      //   console.log(data) 
      //   let reader = new FileReader()
      //   reader.readAsDataURL(data)
      //   const _this = this
      //   reader.onloadend = function(e) {
      //     _this.avatarUrl=reader.result
      //     _this.uploadList=[data]
      //     _this.visible2 = false
      //   } 
      // })
    },
    realTime (data) {
      var previews = data;
      var h = 0.5;
      var w = 0.2;

      this.previewStyle1 = {
        width: previews.w + "px",
        height: previews.h + "px",
        overflow: "hidden",
        margin: "0",
        zoom: h
      };

      this.previewStyle2 = {
        width: previews.w + "px",
        height: previews.h + "px",
        overflow: "hidden",
        margin: "0",
        zoom: w
      };
      this.previews = data;
    },
    // base 64 转file
    dataURLtoFile (dataurl, filename) {//将base64转换为文件
      var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    }
  }
}
</script>
<style lang="scss" scoped>
#user-management-add-update {
  .form-custom {
    .ivu-form-item {
      width: 50%;
      float: left;
      .ivu-input {
        width: 200px;
      }
    }
  }
  .demo-upload-list {
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
    margin-right: 4px;
  }
  .demo-upload-list img {
    width: 100%;
    height: 100%;
  }
  .demo-upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.6);
  }
  .demo-upload-list:hover .demo-upload-list-cover {
    display: block;
  }
  .demo-upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }
  .footer {
    text-align: right;
  }
}
.cropper-content {
  display: flex;
  display: -webkit-flex;
  justify-content: flex-start;
  -webkit-justify-content: flex-start;
  .cropper {
    width: 300px;
    height: 300px;
    margin-right: 10px;
  }
  .show-preview {
    flex: 1;
    -webkit-flex: 1;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
    -webkit-justify-content: center;
    .preview {
      overflow: hidden;
      border-radius: 50%;
      border: 1px solid #cccccc;
      background: #cccccc;
      margin-left: 40px;
    }
  }
}
.footer-btn {
  margin-top: 30px;
  display: flex;
  display: -webkit-flex;
  justify-content: flex-end;
  -webkit-justify-content: flex-end;
  .scope-btn {
    width: 350px;
    display: flex;
    display: -webkit-flex;
    justify-content: space-between;
    -webkit-justify-content: space-between;
  }
  .upload-btn {
    flex: 1;
    -webkit-flex: 1;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
    -webkit-justify-content: center;
  }
  .btn {
    outline: none;
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    -webkit-appearance: none;
    text-align: center;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    outline: 0;
    margin: 0;
    -webkit-transition: 0.1s;
    transition: 0.1s;
    font-weight: 500;
    padding: 8px 15px;
    font-size: 12px;
    border-radius: 3px;
    color: #fff;
    background-color: #67c23a;
    border-color: #67c23a;
  }
}
</style>